<template>
  <el-dialog
    v-model="dialogVisible"
    title="滚动购买权限"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="transfer-container">
      <!-- 顶部选项 -->
      <div class="transfer-options">
        <el-radio-group v-model="selectionType" @change="handleTreeCheckChange">
          <el-radio value="department">选择到部门</el-radio>
          <el-radio value="person">选择到人</el-radio>
        </el-radio-group>
      </div>

      <!-- 搜索框 -->
      <div class="transfer-search">
        <span>请输入过滤关键字</span>
        <el-input v-model="filterText" placeholder="过滤关键字" clearable class="search-input" />
        <el-button type="text" @click="clearFilter">清除</el-button>
      </div>

      <!-- 穿梭框主体 -->
      <div class="transfer-main">
        <!-- 左侧树形面板 -->
        <div class="transfer-panel left-panel">
          <div class="panel-header">统管</div>
          <div class="panel-body">
            <el-tree
              ref="treeRef"
              :data="treeData"
              show-checkbox
              node-key="id"
              :props="treeProps"
              :filter-node-method="filterNode"
              :default-expand-all="defaulEexpandAll"
              @check="handleTreeCheck"
              :key="treeKey"
            />
          </div>
        </div>

        <!-- 中间按钮 -->
        <div class="transfer-buttons">
          <el-button
            type="primary"
            circle
            @click="transferToRight"
            :disabled="leftSelected.length === 0"
          >
            <Icon icon="ep-arrow-right" />
          </el-button>
          <el-button
            type="primary"
            circle
            @click="transferToLeft"
            :disabled="rightSelected.length === 0"
            ><Icon icon="ep-arrow-left" />
          </el-button>
        </div>

        <!-- 右侧列表面板 -->
        <div class="transfer-panel right-panel">
          <div class="panel-header">已选: {{ rightData?.length }}</div>
          <div class="panel-body">
            <el-table
              :data="rightData"
              height="100%"
              border
              @selection-change="handleRightSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" label="名称" />
              <el-table-column width="80">
                <template #default="{ row }">
                  <el-button type="danger" circle size="small" @click="removeItem(row)" plain link>
                    <Icon icon="ep-delete" />
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部按钮 -->
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmSelection">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import type { ElTree } from 'element-plus'
import { getDeptUserTree } from '@/api/roll'
const treeKey = ref(0)
interface TreeNode {
  id: string | number
  label: string
  children?: TreeNode[]
}
const emit = defineEmits(['selectUser'])
const props = defineProps(['userList'])
const dialogVisible = ref(false)
const filterText = ref('')
const selectionType = ref<string>('department')
const defaulEexpandAll = ref(false)
const treeRef = ref<InstanceType<typeof ElTree>>()
const rightData = ref<TreeNode[]>([])
const rightSelected = ref<TreeNode[]>([])

// 左侧树选中的节点
const leftSelected = computed(() => {
  return treeRef.value?.getCheckedNodes(false) || []
})

// 树形数据
const treeData = ref<TreeNode[]>([])

const treeProps = {
  children: 'children',
  label: 'name'
}
const handlegetDeptUserTree = async () => {
  const res = await getDeptUserTree()
  treeData.value = res
}
// 过滤树节点
const filterNode = (value: string, data: TreeNode) => {
  if (!value) return true
  return data.label.includes(value)
}

// 清除过滤
const clearFilter = () => {
  filterText.value = ''
}

// 处理树节点选中
const handleTreeCheck = () => {
  // 可以在这里添加额外的逻辑
}
const handleTreeCheckChange = (name) => {
  defaulEexpandAll.value = name == 'person'
  treeKey.value++
}

// 处理右侧表格选中
const handleRightSelectionChange = (val: TreeNode[]) => {
  rightSelected.value = val
}

// 将选中项转移到右侧
const transferToRight = () => {
  // 获取所有选中的节点（包括半选状态）
  const checkedNodes = treeRef.value?.getCheckedNodes(false) || []

  // 过滤出只有叶子节点（没有children的节点）
  const leafNodes = checkedNodes.filter((node) => !node.children || node.children.length === 0)

  // 去重后添加到右侧
  const newItems = leafNodes.filter(
    (item) => !rightData.value.some((rightItem) => rightItem.id === item.id)
  )

  rightData.value = [...rightData.value, ...newItems]
  // 清空左侧选中状态
  treeRef.value?.setCheckedKeys([])
}

// 将选中项转移到左侧
const transferToLeft = () => {
  const idsToRemove = rightSelected.value.map((item) => item.id)
  rightData.value = rightData.value.filter((item) => !idsToRemove.includes(item.id))
  rightSelected.value = []
}

// 删除单个项
const removeItem = (row: TreeNode) => {
  rightData.value = rightData.value.filter((item) => item.id !== row.id)
}

// 确认选择
const confirmSelection = () => {
  console.log('已选择的数据:', rightData.value)
  emit('selectUser', rightData.value)
  dialogVisible.value = false
  // 这里可以emit事件将数据传递给父组件
}
onMounted(() => {
  handlegetDeptUserTree()
})
// 监听过滤文本变化
watch(filterText, (val) => {
  treeRef.value?.filter(val)
})
watch(
  () => props.userList,
  (val) => {
    if (val && val.length > 0) {
      rightData.value = val.map((item) => ({
        id: item.id,
        name: item.nickName
      }))
    }
  }
)
// 暴露方法给父组件
defineExpose({
  open: () => {
    dialogVisible.value = true
  },
  close: () => {
    dialogVisible.value = false
  }
})
</script>

<style scoped>
.transfer-container {
  display: flex;
  flex-direction: column;
  height: 500px;
}

.transfer-options {
  margin-bottom: 15px;
}

.transfer-search {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.transfer-search span {
  margin-right: 10px;
  font-size: 14px;
  color: #606266;
}

.search-input {
  width: 200px;
  margin-right: 10px;
}

.transfer-main {
  display: flex;
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.transfer-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #ebeef5;
}

.transfer-panel:last-child {
  border-right: none;
}

.panel-header {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
}

.panel-body {
  flex: 1;
  overflow: auto;
  padding: 10px;
}

.left-panel .panel-body {
  padding: 0;
}

.transfer-buttons {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 0 20px;
  background-color: #f5f7fa;
}

.el-tree {
  background: transparent;
}

:deep(.el-tree-node__content) {
  height: 36px;
}

.right-panel .panel-body {
  padding: 0;
}

:deep(.el-table) {
  height: 100%;
}

:deep(.el-table__body-wrapper) {
  overflow-x: hidden;
}
</style>
